/*
 * Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License. You may
 * obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
 * required by applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
package com.superman.mvpframe.client.mvp;

import java.util.Map;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceChangeRequestEvent;
import com.google.web.bindery.event.shared.EventBus;
import com.superman.mvpframe.client.gin.XGinjector;

/**
 * 页面前进后退控制器
 * 
 * @author superman
 * @version 2018年7月5日下午10:17:33
 */
public class MyPlaceController {

	private final EventBus eventBus = XGinjector.INSTANCE.getEventBus();

	private Place where = Place.NOWHERE;

	/**
	 * 返回
	 * 
	 * @author superman
	 * @version 2018年7月5日 下午10:20:01
	 */
	public void back() {
		back(null, null);
	}

	/**
	 * 返回,并且带上上下文
	 * 
	 * @author superman
	 * @version 2018年7月5日 下午10:20:07
	 * @param contextData 携带的上下文参数
	 */
	public void back(Map<String, Object> contextData) {
		back(null, contextData);
	}

	/**
	 * 返回到指定的页面
	 * 
	 * @author superman
	 * @version 2018年7月5日 下午10:20:35
	 * @param place
	 */
	public void back(Place place) {
		back(place, null);
	}

	private void back(Place place, Map<String, Object> contextData) {
		XGinjector.INSTANCE.getPageRouter().back(place, contextData);
	}

	/**
	 * 返回首页
	 * 
	 * @author superman
	 * @version 2018年7月5日 下午10:20:48
	 */
	public void backHome() {
		XGinjector.INSTANCE.getPageRouter().backHome();
	}

	public Place getWhere() {
		return where;
	}

	private String maybeGoTo(Place newPlace) {
		PlaceChangeRequestEvent willChange = new PlaceChangeRequestEvent(newPlace);
		eventBus.fireEvent(willChange);
		String warning = willChange.getWarning();
		return warning;
	}

	/**
	 * 前进到指定的页面
	 * 
	 * @author superman
	 * @version 2018年7月5日 下午10:18:48
	 * @param place 路由
	 */
	public void push(Place place) {
		push(place, null);
	}

	/**
	 * 前进到指定的页面,并且带上上下文
	 * 
	 * @author superman
	 * @version 2018年7月5日 下午10:19:15
	 * @param place 路由
	 * @param contextData 携带的上下文
	 */
	public void push(Place place, Map<String, Object> contextData) {

		if (getWhere().equals(place)) {
			return;
		}

		String warning = maybeGoTo(place);
		if (warning == null) {
			where = place;
			XGinjector.INSTANCE.getPageRouter().push(place, contextData);
		}

	}

}
